﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using NHibernate;
using NHibernate.Criterion;
namespace OpenFuse.Cache.Repositories
{
	[Serializable]
    public class AccountRepository : MarshalByRefObject, Comms.IAccountList
    {
        public void Save(Comms.IAccount a)
        {
            using (ISession session = LocalCache.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(a);
                    transaction.Commit();
                }
        }

        public void Delete(Comms.IAccount a)
        {
            using (ISession session = LocalCache.OpenSession())
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(a);
                    transaction.Commit();
                }
        }

        public Comms.IAccount GetById(string name, string first, string last)
        {
            using (ISession session = LocalCache.OpenSession())
            {
                return session.CreateCriteria(typeof(Account))
                    .Add(Restrictions.Eq("FirstName", first))
                    .Add(Restrictions.Eq("LastName", last))
                    .UniqueResult<Account>();
            }
        }

        public IList<Comms.IAccount> GetAll()
        {
            using (ISession session = LocalCache.OpenSession())
            {
                return session.CreateCriteria(typeof(Account)).List<Comms.IAccount>();
            }
        }
		
        public IList<Comms.IAccount> GetByNick(string nick)
        {
			try{
	            using (ISession session = LocalCache.OpenSession())
	            {
					DetachedCriteria gridHasNick = DetachedCriteria.For<Grid>()
						.Add(Expression.Eq("Nick", nick))
						.SetProjection( Projections.Id());

					
	                return session.CreateCriteria(typeof(Account))
						.Add(Subqueries.PropertyIn("Grid", gridHasNick))
						.List<Comms.IAccount>();
	            }
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
			return null;
        }

		public Comms.IAccount NewAccount()
		{
			return new Account();
		}
    }
}
